package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import java.text.SimpleDateFormat
import org.grails.web.util.WebUtils

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR'])
@Transactional(readOnly = true)
class AttachmentController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond Attachment.list(params), model:[attachmentCount: Attachment.count()]
    }

    def show(Attachment attachment) {
        respond attachment
    }

    def create() {
        def targetUri = request.getHeader("referer")
        respond new Attachment(params), model: [targetUri: targetUri]
    }

    @Transactional
    def save(Attachment attachment) {
        if (attachment == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (attachment.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond attachment.errors, view:'create'
            return
        }

        attachment.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'attachment.label', default: 'Attachment'), attachment.id])
                redirect attachment
            }
            '*' { respond attachment, [status: CREATED] }
        }
    }

    def edit(Attachment attachment) {
        respond attachment
    }

    @Transactional
    def update(Attachment attachment) {
        if (attachment == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (attachment.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond attachment.errors, view:'edit'
            return
        }

        attachment.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'attachment.label', default: 'Attachment'), attachment.id])
                redirect attachment
            }
            '*'{ respond attachment, [status: OK] }
        }
    }

    @Transactional
    def delete(Attachment attachment) {

        if (attachment == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        attachment.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'attachment.label', default: 'Attachment'), attachment.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'attachment.label', default: 'Attachment'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    @Transactional
    def uploadAvatar(Attachment attachment)
    {
        // 图片参数校验

        def file = request.getFile("file")

        if (file.empty)
        {
            flash.message = message(code: '请选择要上传的文件')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }
        def imageExtensionsList = ['jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG']
        def fileExtensionsList = ['pdf', 'doc', 'docx', 'xlsx', 'xls']
        def fileSize = request.getContentLength()
        if (fileSize > 15728640)
        {
            flash.message = message(code: '文件大小不能超过15M')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }
        def fileOrgName = file?.getOriginalFilename()
        def fileType = fileOrgName?.split('\\.')[-1]
        fileType = fileType?.toLowerCase()
        if (!(fileType in imageExtensionsList) && !(fileType in fileExtensionsList))
        {
            flash.message = message(code: '文件格式不支持')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }

        // 将图片临时存储到 images目录中
        def webrootDir = servletContext.getRealPath("/")
        def code = UUID.randomUUID().toString()
        File fileImage = new File(webrootDir, "images/${code}.${fileType}")
        file.transferTo(fileImage)

        attachment.fileName = fileOrgName
        // attachment.fileUrl = "http://crm.combine-tech.cn/static/images/${code}.${fileType}"

        println WebUtils.retrieveGrailsWebRequest().getBaseUrl()

        attachment.fileUrl = WebUtils.retrieveGrailsWebRequest().getBaseUrl() + "/static/images/${code}.${fileType}"

        attachment.description = fileOrgName?.split('\\.')[0]
        def o = [:]
        def files = []
        def sfile = [:]
        if (fileType in imageExtensionsList)
        {
            sfile['thumbnailUrl'] = attachment.fileUrl
        }
        else
        {
            sfile['thumbnailUrl'] = ''
        }
        sfile['name'] = fileOrgName
        files.add(sfile)
        o['files'] = files
        if (attachment.validate())
        {
            attachment.save flush: true
            render o as JSON
        }
        else
        {
            flash.message = message(code: '文件上传失败，请稍后重试')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }
    }
}
